<template>
  <t-adaptive-page
    v-loading="state.loading"
    class="menu_mange"
    tableTitle="合同列表"
    row-key="Id"
    isCopy
    ref="tAdaptivePageRef"
    isExpansion
    :isTTableSelfFilling="false"
    columnSetting
    :table="state.table"
    :columns="state.table.columns"
    isShowWidthSize
    :opts="opts"
    :widthSize="4"
    @submit="conditionEnter"
    @page-change="pageChange"
    @size-change="sizeChange"
    @radio-change="selecUpdateChange"
  >
    <template #index="{ scope }">
      <div>{{ scope.$index + 1 }}</div>
    </template>

    <template #JobNum="{ scope }">
      <div>
        <el-link
          link
          @click="viewCheck(scope.row)"
          type="primary"
          >{{ scope.row.JobNum }}</el-link>
      </div>
    </template>
    <template #CreateDate="{ scope }">
      <div>{{ parseTime(scope.row.createDate,'{y}-{m}-{d}') }}</div>
    </template>
    <template #DDate="{ scope }">
      <div>{{ parseTime(scope.row.Ddate, '{y}-{m}-{d}') }}</div>
    </template>
    <template #State="{ scope }">
      <div @click="viewCheckDetail(scope.row)">
        <el-tag type="info" v-if="scope.row.State == '0'">开立</el-tag>
        <el-tag type="success" v-if="scope.row.State == '2'">已审核</el-tag>
        <el-tag type="primary" v-if="scope.row.State == '1'" >送审中</el-tag>
        <el-tag type="danger" v-if="scope.row.State == '3'">已关闭</el-tag>
      </div>

    </template>
    <template #GDStatus="{ scope }">
      <el-tag type="info" v-if="scope.row.GDStatus == null||scope.row.GDStatus==0">未归档</el-tag>
      <el-tag type="primary" v-if="scope.row.GDStatus == '1'">已归档</el-tag>
    </template>
    <template #IsSale="{ scope }">
      <el-tag type="info" v-if="scope.row.IsSale == null||scope.row.IsSale==0">未生成</el-tag>
      <el-tag type="primary" v-if="scope.row.IsSale == '1'">已生成</el-tag>
    </template>

    <template #BGState="{ scope }">
      <!--
          11:已审核
          12:变更送审
          13:变更不通过
          -->
      <el-tag type="info" v-if="scope.row.BGState == '0' || scope.row.BGState == null"
        >未变更</el-tag
      >
      <el-tag type="warning" v-if="scope.row.BGState == '3'">变更不通过</el-tag>
      <el-tag type="success" v-if="scope.row.BGState == '2'">变更通过</el-tag>
      <el-tag type="primary" v-if="scope.row.BGState == '1'">变更送审中</el-tag>
    </template>

    <template #DeliveryDate="{ scope }">
      <div>{{ parseTime(scope.row.DeliveryDate, '{y}-{m}-{d}') }}</div>
    </template>

    <template #ContractAmount="{ scope }">
      <div>{{ addSeparator(scope.row.ContractAmount) }}</div>
    </template>


    <template #IsMoudel="{ scope }">
      <el-tag :type="scope.row.IsMoudel ? 'primary' : 'success'">{{
        scope.row.IsMoudel ? '是' : '非标合同'
      }}</el-tag>
    </template>
    <template #Type="{ scope }">
      <el-tag :type="scope.row.Type === '0' ? 'primary' : 'success'">{{
        scope.row.Type === '0' ? '正式合同' : '虚拟合同'
      }}</el-tag>
    </template>

    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button
          type="primary"
          size="small"
          @click="handlMultiplex(state.selectedRow)"
          v-if="state.selectedRow &&
          state.selectedRow.State === '2' &&
          (state.selectedRow.BGState == null || state.selectedRow.BGState === '2') &&
          state.selectedRow.IsSale !== '1' &&
          checkPermission('生成订单', state.roleList)"
        >生成订单</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handlChange(state.selectedRow)"
          v-if="state.selectedRow &&
          !['0'].includes(state.selectedRow.Type) &&
          ['2'].includes(state.selectedRow.State) &&
          state.selectedRow.BGState !== '1' &&
          checkPermission('转正式合同', state.roleList)"
        >转正式合同</el-button>
        <el-button
          size="small"
          type="primary"
          @click="handlCheck(state.selectedRow)"
          v-if="state.selectedRow && state.selectedRow.State === '0' &&
          checkPermission('提交', state.roleList)"
        >提交</el-button>
        <el-button size="small"  type="primary" @click="versionHandle(state.selectedRow)" v-if="state.selectedRow && checkPermission('查看版本', state.roleList)">查看版本</el-button>
        <el-button size="small" type="primary" @click="printHandle(state.selectedRow)" v-if="state.selectedRow && checkPermission('打印', state.roleList)">打印</el-button>
        <el-button size="small" type="primary" @click="handlEedit(state.selectedRow)" v-if="state.selectedRow && ['0'].includes(state.selectedRow.State) && checkPermission('修改', state.roleList)">编辑</el-button>
        <el-button size="small" type="primary" @click="handlGbCheck(state.selectedRow, '3')" v-if="state.selectedRow && state.selectedRow.State !== '3' && checkPermission('关闭', state.roleList)">关闭</el-button>
        <el-button size="small" type="primary" @click="updateCheck(state.selectedRow)" v-if="state.selectedRow && ['2'].includes(state.selectedRow.State) && state.selectedRow.BGState !== '1' && checkPermission('变更', state.roleList)">变更</el-button>
        <el-button size="small" type="primary" @click="updateFileCheck(state.selectedRow)" v-if="state.selectedRow && ['2'].includes(state.selectedRow.State) && state.selectedRow.BGState !== '1' && checkPermission('变更', state.roleList)">上传附件</el-button>
        <el-button size="small" type="danger" @click="deleteHandles(state.selectedRow)" v-if="state.selectedRow && ['0'].includes(state.selectedRow.State) && checkPermission('删除', state.roleList)">删除</el-button>
        <el-button size="small" type="primary" @click="viewCheckDetail(state.selectedRow)" >查看审核进度</el-button>
      </div>
      <div v-else style="color:red">
        选择数据后显示操作按钮
      </div>

    </template>

    <template #footerBtn>

      <el-button size="small" type="danger" @click="addHandle()">新增</el-button>
      <el-button size="small" type="danger" @click="importHandle()" >导入</el-button>
      <!-- <el-button size="small" type="danger" @click="importHandle()">导入</el-button> -->

      <el-button size="small" type="primary" @click="tAdaptivePageRef.TQueryConditionPage.checkHandle()">查询</el-button>
      <el-button size="small" type="danger" @click="tAdaptivePageRef.TQueryConditionPage.resetHandle()">重置</el-button>
    </template>
  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog
      :title="state.title"
      width="100%"
      v-model="state.dialogSelectEnt"
      draggable
      top="10px"
      :close-on-click-modal="false"
  >
    <div>
      <div class="pb10" v-if="state.isAdd">
      </div>

      <el-tabs type="border-card" v-model="state.selectpane" >
        <el-tab-pane label="基本信息" name="d01">
          <EntryBaseInfo
              ref="formRef"
              :isShowSubBut="state.isShowSubBut"
              :loading="lding"

              :isBg="state.isBg"
              :isAdd="state.isAdd"
              :baseInfo="state.formData.Main"
              :rules="state.rules"
              :tremZF="state.formData.TremZF"
              :subList="state.formData.SubList"
              Id="10007"
              @update:SubList="updateSubList"
          ></EntryBaseInfo>
        </el-tab-pane>

        <!--  1 质量保证条款 2所有权条款 3解决争议条款 4不可抗力条款 5解除合同条款 6违约条款 7支付条款        -->
        <el-tab-pane label="质量保证条款" name="d02">
          <EntryQualityInfo
              ref="TremQA"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremQA"
              Id="10001"
              title="质量保证条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="所有权利转移条款" name="d03">
          <EntryQualityInfo
              ref="TremTO"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremTO"
              Id="10002"
              title="所有权利转移条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="解决争议条款">
          <EntryQualityInfo
              ref="TremDR"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremDR"
              Id="10003"
              title="解决争议条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="不可抗力条款" name="d04">
          <EntryQualityInfo
              ref="TremFM"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremFM"
              Id="10004"
              title="不可抗力条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="违约条款" name="d05">
          <EntryQualityInfo
              ref="TremD"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremD"
              Id="10006"
              title="违约条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="解除合同条款" name="d06">
          <EntryQualityInfo
              ref="TremTC"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremTC"
              Id="10005"
              title="解除合同条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="签收验收方式" name="d07">
          <EntryOwner
              ref="TremYS"
              :isBg="state.isBg"
              :isShowSubBut="state.isShowSubBut"
              v-model:Trem="state.formData.TremYS"
              Id="10012"
              title="签收验收方式"
          ></EntryOwner>
        </el-tab-pane>
        <el-tab-pane label="其他" name="d08">
          <EntryQualityInfo
              ref="TremOther"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremOther"
              Id="10008"
              title="其他"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="保密约定" name="d09">
          <EntryQualityInfo
              ref="TremBM"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremBM"
              Id="10009"
              title="保密约定"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="交付条款" name="d10">
          <EntryQualityInfo
              ref="TremJF"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremJF"
              Id="10011"
              title="交付条框"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="包装条款" name="d11">
          <EntryQualityInfo
              ref="TremBZ"
              :isShowSubBut="state.isShowSubBut"
              :isBg="state.isBg"
              v-model:Trem="state.formData.TremBZ"
              Id="10010"
              title="包装条款"
          ></EntryQualityInfo>
        </el-tab-pane>
        <el-tab-pane label="附件资料" name="d12">

          <!-- <EntryAnnex
          v-if="ishowfile"
              ref="ContractFile"
              :isShowSubBut="state.isShowUpFile"
              :Id="state.selectedRow?.Id"
              :Trem="state.formData.ContractFile"
              v-model="state.formData.ContractFile"
              title="附件资料"
          ></EntryAnnex> -->
  <EntryAnnex

              ref="ContractFile"
              :isShowSubBut="state.isShowUpFile"
              :Id="state.selectedRow?.Id"
              :Trem="state.formData.ContractFile"
              v-model="state.formData.ContractFile"
              title="附件资料"
          ></EntryAnnex>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button

            type="primary"
            @click="submitForm"
            :loading="lding"
        >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>

  <!-- 用户导入对话框 -->
  <el-dialog
      v-loading="state.upload.loading"
      :title="state.upload.title"
      v-model="state.upload.open"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeFile"
  >
    <el-upload
        ref="uploadRef111"
        action="#"
        drag
        :auto-upload="false"
        :on-change="onChange"
        :before-remove="beforeRemove"
        :file-list="fileList"
        :before-upload="beforeUpload"
        multiple
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!--            <el-link-->
          <!--              type="primary"-->
          <!--              :underline="false"-->
          <!--              style="font-size: 12px; vertical-align: baseline"-->
          <!--              @click="importTemplate"-->
          <!--              >下载模板</el-link-->
          <!--            >-->
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="state.upload.loading"
        >确 定</el-button
        >
        <el-button @click="closeFile">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="state.drawer.open" :title="state.drawer.title" direction="rtl" size="50%">
    <el-table :data="state.drawer.gridData">
      <el-table-column property="versionNum" label="版本号" width="150" />
      <el-table-column property="ContractNum" label="合同号" width="150" />
      <el-table-column property="BGState" label="状态">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.BGState == '0' || scope.row.BGState == null"
          >未变更</el-tag
          >
          <el-tag type="warning" v-if="scope.row.BGState == '3'">变更不通过</el-tag>
          <el-tag type="success" v-if="scope.row.BGState == '2'">变更通过</el-tag>
          <el-tag type="primary" v-if="scope.row.BGState == '1'">变更送审中</el-tag>
        </template>
      </el-table-column>

      <el-table-column property="updateDate" label="版本时间" width="200">
        <template #default="scope">
          {{ parseTime(scope.row.updateDate) }}
        </template>
      </el-table-column>
      <el-table-column property="updateBy" label="修改人" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>


  <!-- 审批流程详情对话框 -->
  <el-dialog
      v-loading="state.checkData.loading"
      :title="state.checkData.title"
      v-model="state.checkData.dialog"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeFile">
    <ProcessInstanceTaskList :loading="state.checkData.loading" :tasks="state.checkData.data"></ProcessInstanceTaskList>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeFile">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 合同详情对话框 -->
  <el-dialog
      top="10px"
      v-loading="state.formViewData.loading"
      :title="state.formViewData.title"
      v-model="state.formViewData.dialog"
      v-if="state.formViewData.dialog"
      width="100%"
      append-to-body
      :before-close="closeFile">
    <el-tabs type="border-card" v-model="state.selectpane">
      <el-tab-pane label="基本信息" name="d01">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>基本信息</span>
            </span>
        </template>
        <DetailBaseInfo
            style="width: 100%"
            ref="formRef"
            :isShowSubBut="false"
            :loading="lding"
            :isBg="state.isBg"
            :isAdd="state.isAdd"
            :baseInfo="state.formViewData.data.Main"
            :rules="state.rules"
            :tremZF="state.formViewData.data.TremZF"
            :subList="state.formViewData.data.SubList"
            Id="10007"
            @update:SubList="updateSubList"
        ></DetailBaseInfo>
      </el-tab-pane>

      <!--  1 质量保证条款 2所有权条款 3解决争议条款 4不可抗力条款 5解除合同条款 6违约条款 7支付条款        -->
      <el-tab-pane label="质量保证条款" name="d02">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>质量保证条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremQA"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremQA"
            Id="10001"
            title="质量保证条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="所有权利转移条款" name="d03">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>所有权利转移条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremTO"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremTO"
            Id="10002"
            title="所有权利转移条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="解决争议条款">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>解决争议条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremDR"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremDR"
            Id="10003"
            title="解决争议条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="不可抗力条款" name="d04">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>不可抗力条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremFM"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremFM"
            Id="10004"
            title="不可抗力条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="违约条款" name="d05">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>违约条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremD"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremD"
            Id="10006"
            title="违约条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="解除合同条款" name="d06">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>解除合同条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremTC"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremTC"
            Id="10005"
            title="解除合同条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="签收验收方式" name="d07">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>签收验收方式</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremYS"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremYS"
            Id="10012"
            title="签收验收方式"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="其他" name="d08">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>其他</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremOther"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremOther"
            Id="10008"
            title="其他"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="保密约定" name="d09">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>保密约定</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremBM"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremBM"
            Id="10009"
            title="保密约定"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="交付条款" name="d10">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>交付条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremJF"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremJF"
            Id="10011"
            title="交付条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="包装条款" name="d11">
        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>包装条款</span>
            </span>
        </template>
        <DetailQualityInfo
            ref="TremBZ"
            :isShowSubBut="state.isShowSubBut"
            :isBg="state.isBg"
            v-model:Trem="state.formViewData.data.TremBZ"
            Id="10010"
            title="包装条款"
        ></DetailQualityInfo>
      </el-tab-pane>
      <el-tab-pane label="附件资料" name="d12">

        <template #label>
            <span class="custom-tabs-label">
              <span style="color: red">*</span>
              <span>附件资料</span>
            </span>
        </template>
        <DetailAnnex
            ref="ContractFile"
            :isShowSubBut="state.isShowUpFile"
            :Id="state.selectedRow?.Id"
            :Trem="state.formViewData.data.ContractFile"
            v-model="state.formViewData.data.ContractFile"
            title="附件资料"
        ></DetailAnnex>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeFile">关 闭</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="tsx">
import {computed, onMounted, reactive, ref, toRefs, unref} from 'vue'
import {
  ApproveDocument,
  ApproveDocumentCheck,
  findbaseBasicManage,
  findProcessInfo,
  getContractInfo,
  importE,
  userRole
} from '@/api/base'
import {contractImport, delHT, generateOrder, getContractVersion, getHTByPage, SaveQCHT} from '@/api/contract_entry'
import {addSeparator, checkPermission, debounce, parseTime} from '@/utils/util'
import {cubasdocStore} from '@/stores/modules/cubasdoc'
import {ElMessage} from 'element-plus'
import EntryBaseInfo from './components/base_info.vue'
import EntryQualityInfo from './components/quality_info.vue'
import EntryOwner from './components/ownership_info.vue'
import EntryAnnex from './components/annex_info.vue'
import {checkFildsStore} from '@/stores/modules/checkFilds'
import {emitter} from "@/hooks/evenBus"
import {useRouter} from "vue-router";
import ProcessInstanceTaskList from '@/components/ProcessInstance/ProcessInstanceTaskList.vue'

import DetailBaseInfo from './detail/base_info.vue'
import DetailQualityInfo from './detail/quality_info.vue'
import DetailAnnex from './detail/annex_info.vue'

const tAdaptivePageRef: any = ref(null)
const router = useRouter()
const cubasdoc = cubasdocStore()
const ishowfile=ref(false)
//const emitter= mitt()

const handlEedit = async (row: any) => {
  clearCondition()
  if(row.Type=='1'||row.State=='2')
{
  ishowfile.value=true
}
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === 'OK') {
    state.formData = res.Data
    console.log(state.formData);
    if (state.formData.SubList2?.length > 0) {
      state.formData.SubList = state.formData.SubList2
    }

    if (state.formData.Main.PhasedFile) {
      //转换为数组
      state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(',')
    } else {
      state.formData.Main.PhasedFile = []
    }
    if (state.formData.Main.Payment) {
      //转换为数组
      state.formData.Main.Payment = state.formData.Main.Payment.split(',')
    } else {
      state.formData.Main.Payment = []
    }
    if (state.formData.Main.TDYSJDFile) {
      //转换为数组
      state.formData.Main.TDYSJDFile = state.formData.Main.TDYSJDFile.split(',')
    } else {
      state.formData.Main.TDYSJDFile = []
    }
    if (state.formData.Main.JHYSJDFile) {
      //转换为数组
      state.formData.Main.JHYSJDFile = state.formData.Main.JHYSJDFile.split(',')
    } else {
      state.formData.Main.JHYSJDFile = []
    }

    if (state.formData.Main.JSJDFile) {
      //转换为数组
      state.formData.Main.JSJDFile = state.formData.Main.JSJDFile.split(',')
    } else {
      state.formData.Main.JSJDFile = []
    }

    state.isBg = false
    state.formData.Type = 'BJ'
    state.isShowSubBut = false
    state.dialogSelectEnt = true
    state.title = '修改合同录入'
    state.isAdd = false
  }
}

const fileList = ref([])
const ACCEPTED_EXTENSIONS = ['doc', 'xls', 'ppt', 'txt', 'pdf', 'png', 'jpg', 'jpeg']


//组装导入数据,将数据插入到state.table.data中，判断Id是否为空且存在，为真则修改，为假则新增
function importListAssemble(list,tableData) {
  list.forEach(item => {
    //重新计算
    item.Rate = item.Rate || 13
    // item.RowState = (item.BgRemark && item.BgRemark.trim() === '12.取消整项内容') ? '0' : '1'
    item.RowState =  '1'
    // let invData = {
    //   Code: item.CinvCode,
    // }
    // GetInventory2(invData).then(({ Data }) => {
    //   if (!Data){
    //     ElNotification.error({
    //       title: '提示',
    //       message: "【"+item.CinvCode+"】存货不存在，请检查存货编码是否正确！",
    //       offset: 200,
    //     })
    //     return
    //   }
    //   let invoptions = Data[0]
    //   //赋值
    //   item.CinvName = invoptions.cInvName
    //   item.Unit = invoptions.cComUnitCode
    // })

    numChange2(item)
    // tableData.push({ ...item,LineNum: tableData.length + 1 })
    if (item.Id && item.Id.trim() !== '') {
      const existingItemIndex = tableData.findIndex(existingItem => existingItem.Id === item.Id)
      if (existingItemIndex !== -1) {
        tableData[existingItemIndex] = { ...tableData[existingItemIndex], ...item }
      } else {
        tableData.push({ ...item,LineNum: tableData.length + 1 })
      }
    } else {
      tableData.push({ ...item,LineNum: tableData.length + 1 })
    }
  })
}

function numChange2 (row) {
  let rate = (row.Rate /100) + 1
  row.Amount= (Number(row.Quantity || 0) * Number(row.Price || 0)).toFixed(2)//含税金额
  row.iNatPrice=(Number(row.Price || 0) / rate).toFixed(6)//不含税单价=含税单价 / 1.13
  row.Tax=( (row.Amount || 0) - ((row.Amount || 0) / rate)).toFixed(2)//税额
  row.iNatAmount=((row.Amount || 0 ) - row.Tax).toFixed(2)//不含税金额 = 含税金额 * 1.13
}



const importInitData=(data)=>{
  //处理公司信息
  if (data && data.CustCode){
    let cusoptions = cubasdoc.data.filter((its) => {
      return (its.ccusabbname.toLowerCase().includes(data.CustCode.toLowerCase()))
    })[0]
    if (cusoptions){
      //赋值ccusabbname
      data.CustCode = cusoptions.cCusCode
      data.CustName = cusoptions.ccusabbname
      data.CustAdd = cusoptions.ccusAddress
      data.Tax = cusoptions.cCusRegCode
      data.BankCode = cusoptions.ccusbank
      data.BankAccount = cusoptions.ccusaccount
    }
  }

  //处理销售人员信息
  if (data && data.SaleCode){
    //过滤业务员
    let useroptions = state.userList.filter(its =>
      its.cPsn_Name.toLowerCase().includes(data.SaleCode.toLowerCase())
    )
    if (useroptions) {
      //赋值
      data.SaleName = useroptions[0].cPsn_Name
      data.SaleCode = useroptions[0].cPsn_Num
    }
  }
}




/**
 * 请求前判断文件是否符合要求
 * 如果符合则添加到上传队列
 */
function beforeUpload(file) {
  const extension = file.name.split('.').pop().toLowerCase()
  if (!ACCEPTED_EXTENSIONS.includes(extension)) {
    ElNotification.error({
      title: '提示',
      message: '仅支持 doc, xls, ppt, txt, pdf, png, jpg 和 jpeg 格式的文件',
      offset: 200
    })
    return false
  }
  return true
}

/**
 * 文件选择改变时触发
 */
function onChange(file, fileListVal) {
  fileList.value = fileListVal
}

function beforeRemove(file, fileListVal) {
  fileList.value = fileListVal
}

const closeFile = () => {
  console.log('closeFile')
  fileList.value = []
  state.upload.open = false
  state.checkData.dialog = false
  state.formViewData.dialog = false
}

let uploadRef111 = ref()
/** 提交上传文件 */
async function submitFileForm() {
  if (fileList.value.length === 0) {
    ElNotification.error({
      title: '提示',
      message: '请选择要上传的文件',
      offset: 200
    })
    return
  }

  const file = fileList.value[0].raw
  if (!file) return
  state.upload.loading = true

  try {
    let data= await importE({file:file})

    /*state.formData = {
      ...data.data,
      IsBL:'是',
    }
    let tableData = []

    if (state.formData.SubList?.length > 0) {
      importListAssemble(state.formData.SubList ,tableData)
    }
    importInitData(state.formData.Main)

    state.formData.Main ={
      ...state.formData.Main,
      Ddate: parseTime(new Date(), '{y}-{m}-{d}'),
      DDate2: parseTime(new Date(), '{y}-{m}-{d}'),
      Rate: 13,
      IsMoudels: false,
      IsMoudel: false,
      IsCompliance: true,
      PhasedFile: [],
      JSJDFile: [],
      TDYSJDFile: [],
      JHYSJDFile: [],
    }*/

    ElNotification.success({
      title: '提示',
      message: "【" + file.name + "】导入成功，请检查数据后提交！",
      offset: 200,
    })
    // state.isAdd = true
    // state.isBg = true
    // state.dialogSelectEnt = true
    // state.isShowSubBut = true

    setTimeout(async () => {
      await getData()
    },500)

    closeFile()
  } catch (error) {
    console.log(error);
    ElNotification.error({
      title: '提示',
      message: "【" + file.name + "】导入错误，请检查文件是否正确！",
      offset: 200,
    })
    // 这里可以添加错误提示
  }finally {
    state.upload.loading = false
  }
}

// 上传前
const handleChange = rawFile => {

}

const handleUpload = async file => {
  let fd = new FormData()
  fd.append('file', file.file)
  // 这里是申请上传接口
  let result = await contractImport(fd)
  if (result.code == 200) {
    result.data
    // 去掉 form 表单验证的 *
    // formRef.value.clearValidate(['appLogo'])
    // 上传胜利清空文件
    handleFileSuccess(file, result, [])
  } else {
    ElMessage.error(result.message)
    handleFileSuccess(file, result, [])
  }
}
const updateFileCheck=async(row:any)=>
{
  //console.log(state.formData.ContractFile);
  ishowfile.value=true
 // state.formData.ContractFile=[];
  clearCondition()
  let res = await getContractInfo({ id: row.Id })
  if (res.Code === 'OK') {
    state.formData = res.Data
    state.formData.Type = 'BG'
    state.formData.Main.IsMoudels = false
    if (state.formData.SubList2) {
      state.formData.SubList = state.formData.SubList2
    }
  }
  console.log(state.formData);
  state.isShowSubBut = false
  state.isShowUpFile=true
  state.isBg = false

  state.isAdd = false
  if (state.formData.Main.PhasedFile) {
      //转换为数组
      state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(',')
    } else {
      state.formData.Main.PhasedFile = []
    }
    if (state.formData.Main.Payment.length > 0) {
      //转换为数组
      state.formData.Main.Payment = state.formData.Main.Payment.split(',')
    } else {
      state.formData.Main.Payment = []
    }

    if (state.formData.Main.TDYSJDFile) {
      //转换为数组
      state.formData.Main.TDYSJDFile = state.formData.Main.TDYSJDFile.split(',')
    } else {
      state.formData.Main.TDYSJDFile = []
    }
    if (state.formData.Main.JHYSJDFile) {
      //转换为数组
      state.formData.Main.JHYSJDFile = state.formData.Main.JHYSJDFile.split(',')
    } else {
      state.formData.Main.JHYSJDFile = []
    }

    if (state.formData.Main.JSJDFile) {
      //转换为数组
      state.formData.Main.JSJDFile = state.formData.Main.JSJDFile.split(',')
    } else {
      state.formData.Main.JSJDFile = []
    }


    state.dialogSelectEnt = true
    state.selectpane="d12"
    state.title = '附件上传'
}
const updateCheck = async (row: any) => {
  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === 'OK') {
    state.formData = res.Data
    state.formData.Type = 'BG'
    state.formData.Main.IsMoudels = false
    if (state.formData.SubList2) {
      state.formData.SubList = state.formData.SubList2
    }

    state.isShowSubBut = true
    state.isBg = false
    state.isAdd = false

    if (state.formData.Main.PhasedFile) {
      //转换为数组
      state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(',')
    } else {
      state.formData.Main.PhasedFile = []
    }
    if (state.formData.Main.Payment.length > 0) {
      //转换为数组
      state.formData.Main.Payment = state.formData.Main.Payment.split(',')
    } else {
      state.formData.Main.Payment = []
    }

    if (state.formData.Main.TDYSJDFile) {
      //转换为数组
      state.formData.Main.TDYSJDFile = state.formData.Main.TDYSJDFile.split(',')
    } else {
      state.formData.Main.TDYSJDFile = []
    }
    if (state.formData.Main.JHYSJDFile) {
      //转换为数组
      state.formData.Main.JHYSJDFile = state.formData.Main.JHYSJDFile.split(',')
    } else {
      state.formData.Main.JHYSJDFile = []
    }

    if (state.formData.Main.JSJDFile) {
      //转换为数组
      state.formData.Main.JSJDFile = state.formData.Main.JSJDFile.split(',')
    } else {
      state.formData.Main.JSJDFile = []
    }
    state.dialogSelectEnt = true
    state.title = '变更合同'
  }
}

const viewCheck = async (row: any) => {
  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === 'OK') {
    state.formViewData.data = res.Data

    if (state.formViewData.data.Main.PhasedFile) {
      //转换为数组
      state.formViewData.data.Main.PhasedFile = state.formViewData.data.Main.PhasedFile.split(',')
    } else {
      state.formViewData.data.Main.PhasedFile = []
    }
    if (state.formViewData.data.Main.Payment?.length > 0) {
      //转换为数组
      state.formViewData.data.Main.Payment = state.formViewData.data.Main.Payment.split(',')
    } else {
      state.formViewData.data.Main.Payment = []
    }
    if (state.formViewData.data.Main.TDYSJDFile) {
      //转换为数组
      state.formViewData.data.Main.TDYSJDFile = state.formViewData.data.Main.TDYSJDFile.split(',')
    } else {
      state.formViewData.data.Main.TDYSJDFile = []
    }
    if (state.formViewData.data.Main.JHYSJDFile) {
      //转换为数组
      state.formViewData.data.Main.JHYSJDFile = state.formViewData.data.Main.JHYSJDFile.split(',')
    } else {
      state.formViewData.data.Main.JHYSJDFile = []
    }

    if (state.formViewData.data.Main.JSJDFile) {
      //转换为数组
      state.formViewData.data.Main.JSJDFile = state.formViewData.data.Main.JSJDFile.split(',')
    } else {
      state.formViewData.data.Main.JSJDFile = []
    }


    state.formViewData.title = '合同详情'
    state.formViewData.dialog = true
  }
}

const handlGbCheck = async (row: any, status: any) => {
  //弹窗确认
  ElMessageBox.confirm('确认关闭工作号为【'+row.JobNum+'】的合同？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //调用查询合同详细信息
    const ids = [row.Id]
    let data = {
      Ids: ids, //单据id
      Type: 'HTLR', //类型 HTLR 合同录入 TDYS 通电验收  FHYS 发货验收  JSD 结算单  SKJH 收款计划 SKD 收款单 YKP 预收款发票
      State: status
    }
    await ApproveDocument(data)
    ElNotification.success({
      title: '提示',
      message: '成功',
      offset: 200
    })
    await getData()
  })
}

//viewCheckDetail
const viewCheckDetail = async (row) => {
  let data= await findProcessInfo({Id:row.Id})
  console.log(data,"审批数据")
  if (data.status=='1') {
    state.checkData.data=data.data
    state.checkData.dialog = true
    state.checkData.title = '审批详情'
  }

}



const handlCheck = async (row: any) => {
  //调用查询合同详细信息
  // const ids = row.Id ? [row.Id] : state.ids;
  let data = {
    id: row.Id
  }
  await ApproveDocumentCheck(data)
  ElNotification.success({
    title: '提示',
    message: '提交成功',
    offset: 200
  })
  await getData()
}

const handleView = async (row: any) => {
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === 'OK') {
    state.formData = res.Data
    state.dialogSelectEnt = true
    state.isShowSubBut = false
    state.title = '查询合同版本--' + row.ContractNum + '-v' + row.versionNum
  }
}

// 复用模板
const handlMultiplex = async (row: any) => {
  const ids = row.Id ? [row.Id] : state.ids

  ElMessageBox.confirm('确认生成工作号为【'+row.JobNum+'】的合同订单？请仔细核对数据，生成后将无法撤回！', '审核提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await generateOrder({ Ids: ids })
      if (res.code === 1) {
        ElNotification.success({
          title: '提示',
          message: '生成成功',
          offset: 200
        })
        await getData()
      } else
        ElNotification.error({
          title: '提示',
          message: res.news,
          offset: 200
        })

      await getData()
    })
    .catch(() => {})
}

const handleDelete = (row: any) => {

  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}
const formatter=(rows,cel,cellvalue,index)=>
{
   return cellvalue==1?"已归档":"未归档"
}
const lding=ref(false);
//表格配置
const state: any = reactive({
  roleList: [],
  selectedRow: null,
  selectpane:"d01",//绑定tabs选项，默认第一个选项
  queryData: {
    ContractType: null, //合同类型
    CustCode: null, //客户编码
    CustName: null, //客户名称
    ContractNum: null, //合同号
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null, //建单人
    IsMoudels: null
  },
  table: {
    border: true,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layout: 'total,sizes, slot, prev, pager, next, jumper',
    prevText: '上一页',
    nextText: '下一页',
    // 接口返回数据
    data: [],
    firstColumn: { type: 'radio', fixed: true },
    // 表头数据
    columns: [
      { prop: 'index', label: '序号', minWidth: 55, slotName: 'index',fixed: 'left' },
      { prop: 'JobNum', label: '工作号', minWidth: 120,slotName: 'JobNum',fixed: 'left' },
      { prop: 'GDStatus', label: '归档状态', minWidth: 90,slotName:'GDStatus'},
      // { prop: 'ContractNum', label: '合同编码', minWidth: 120 },
      { prop: 'CustName', label: '客户名称', minWidth: 200 },
      // { prop: 'ContractName', label: '合同名称', minWidth: 120 },
      { prop: 'ProjectName', label: '项目名称', minWidth: 200 },
      { prop: 'ContractAmount', label: '合同总价(元)', minWidth: 110,slotName: 'ContractAmount' },
      { prop: 'DeliveryDate', label: '交付日期', minWidth: 110, slotName: 'DeliveryDate' },
      // { prop: 'DeliveryLocation', label: '交付地点', minWidth: 160 },
      // { prop: 'CustCode', label: '客户编码', minWidth: 120 },

      // { prop: 'CustAdd', label: '客户地址', minWidth: 200 },
      { prop: 'Type', label: '合同类型', minWidth: 100, slotName: 'Type' },
      { prop: 'IsMoudel', label: '合同模板', minWidth: 100, slotName: 'IsMoudel' },
      { prop: 'State', label: '状态', minWidth: 70, slotName: 'State' },
      { prop: 'IsSale', label: '销售订单', minWidth: 100, slotName: 'IsSale' },
      { prop: 'BGState', label: '变更状态', minWidth: 100, slotName: 'BGState' },

      // { prop: 'BankAccount', label: '银行账户', minWidth: 120 },
      // { prop: 'Tax', label: '税号', minWidth: 200 },
      // { prop: 'BankCode', label: '行号', minWidth: 160 },
      // { prop: 'SigningLocation', label: '签订地点', minWidth: 160 },
      { prop: 'versionNum', label: '版本', minWidth: 60 },

      { prop: 'Ddate', label: '单据日期', minWidth: 100, slotName: 'DDate' },
      { prop: 'createDate', label: '制单时间', minWidth: 100, slotName: 'CreateDate' },
      { prop: 'createBy', label: '建单人', minWidth: 80 },
    ],

  },
  selecthttypechange:null,
  loading: false,
  isShowSubBut: true,
  isShowUpFile:false,
  isBg: false,
  title: '新增合同录入',
  dialogSelectEnt: false,
  //表单
  formData: {
    Main: {},
    SubList: [],
    TremZF: [],
    TremTO: [],
    TremTC: [],
    TremQA: [],
    TremFM: [],
    TremDR: [],
    TremD: [],
    TremOther: [],
    TremYS: [],
    TremBM: [],
    TremJF: [],
    TremBZ: [],
    ContractFile: []
  },
  coseData: [],

  clumTable: {
    border: true,
    firstColumn: { type: 'selection' },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: 'CinvCode',
        label: '设备编码'
      },
      {
        prop: 'CinvName',
        label: '设备名称'
      },
      {
        prop: 'CinvAdd',
        label: '规格型号'
      },
      // {
      //   prop: "Price",
      //   label: "单价",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: 'Qty',
        label: '数量',
        canEdit: true,
        configEdit: {
          label: '数量',
          type: 'input',
          editComponent: 'el-input'
        }
      },
      // {
      //   prop: "Amount",
      //   label: "金额",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: 'Unit',
        label: '单位'
      }
    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: '上层',
          key: '1'
        },
        {
          label: '中层',
          key: '2'
        },
        {
          label: '下层',
          key: '3'
        }
      ]
    },
    operator: [
      {
        text: '删除',
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: 'right', // 固定列表右边（left则固定在左边）
      width: 300,
      label: '操作'
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: 'selection' },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: 'CinvCode',
        label: '设备编码'
      },
      {
        prop: 'CinvName',
        label: '设备名称'
      },
      {
        prop: 'CinvAdd',
        label: '规格型号'
      },
      {
        prop: 'Quantity',
        label: '数量'
      },
      {
        prop: 'Unit',
        label: '单位'
      }
    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: '上层',
          key: '1'
        },
        {
          label: '中层',
          key: '2'
        },
        {
          label: '下层',
          key: '3'
        }
      ]
    },
    operator: [
      {
        text: '删除',
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: 'right', // 固定列表右边（left则固定在左边）
      width: 200,
      label: '操作'
    }
  },

  rules: {
    ContractNum: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
    // ProjectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    CustCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
    // ContractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
    // PSType: [{ required: true, message: '请输入评审类型', trigger: 'blur' }],
    // Payment: [{ required: true, message: '请选择支付款项', trigger: 'change' }],
    // BankCode: [{ required: true, message: '请输入开户行', trigger: 'blur' }],
    // BankAccount: [{ required: true, message: '请输入银行账号', trigger: 'blur' }],
    // Tax: [{ required: true, message: '请输入税号', trigger: 'blur' }],
    // IsCompliance: [{ required: true, message: '请选择标的物是否合规', trigger: 'change' }],
    // DeliveryDate: [{ required: true, message: '请选择交付时间', trigger: 'change' }],
    // DeliveryLocation: [{ required: true, message: '请输入交付地点', trigger: 'blur' }],
    // Rate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
    // Unload: [{ required: true, message: '请选择卸货方式', trigger: 'change' }],
    // PackRequirement: [{ required: true, message: '请输入包装要求', trigger: 'blur' }],
    ContractAmount: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
    // IsInstall: [{ required: true, message: '请选择是否安装', trigger: 'change' }],
    // SigningLocation: [{ required: true, message: '请输入签订地点', trigger: 'blur' }],
    // IsMoudel: [{ required: true, message: '请选择合同是否合同模板', trigger: 'change' }],
    // Ddate: [{ required: true, message: '请选择签订日期', trigger: 'blur' }],
    // DDate2: [{ required: true, message: '请选择单据日期', trigger: 'blur' }],
    JobNum: [{ required: true, message: '工作号', trigger: 'blur' }],
    // SaleNum: [{ required: true, message: '售前号', trigger: 'blur' }],
    // Change: [{ required: false, message: '请输入变更原因', trigger: 'blur' }],
    // PhasedFile: [{ required: true, message: '请选择阶段性文件', trigger: 'change' }],
    // TDYSJDFile: [{ required: true, message: '请选择通电验收阶段性文件', trigger: 'change' }],
    // JHYSJDFile: [{ required: true, message: '请选择交货验收阶段性文件', trigger: 'change' }],
    // JSJDFile: [{ required: true, message: '请选择结算阶段性文件', trigger: 'change' }],
    // IsYKP: [{ required: true, message: '请选择是否预开票', trigger: 'change' }],
    // IsBL: [{ required: true, message: '请选择是否补录', trigger: 'change' }],
    // SaleCode: [{ required: true, message: '请选择业务员', trigger: 'change' }]
  },
  defaultSelectVal: [],
  ids: [],
  upload: {
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      // "Content-type": "multipart/form-data"
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/api/Base/ImportExcel',
    loading:false
  },
  drawer: {
    open: false,
    title: '历史版本',
    width: '1000px',
    gridData: []
  },
  tablecz: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layout: 'total,sizes, slot, prev, pager, next, jumper',
    prevText: '上一页',
    nextText: '下一页',
    // 接口返回数据
    data: [],
    firstColumn: { type: 'selection', fixed: true },
    // 表头数据
    columns: [
      { prop: 'ContractName', label: '模板名称', minWidth: 120 },
      { prop: 'CustCode', label: '客户编码', minWidth: 120 },
      { prop: 'CustName', label: '客户名称', minWidth: 200 },
      { prop: 'versionNum', label: '版本号', minWidth: 220 },
      { prop: 'CustAdd', label: '客户地址', minWidth: 200 },
      { prop: 'Type', label: '合同类型', minWidth: 120, slotName: 'Type' },
      { prop: 'ProjectName', label: '项目名称', minWidth: 200 },
      { prop: 'ContractAmount', label: '合同总价', minWidth: 160 },
      { prop: 'createDate', label: '创建时间', minWidth: 220, slotName: 'CreateDate' },
      { prop: 'createBy', label: '建单人', minWidth: 220 }
    ]
  },
  isAdd: false,
  exportConfig: [ // 导出Excel表格配置
    {
      title: '*序号',
      key: 'LineNum',
      type: 'text'
    },
    {
      title: '存货编码',
      key: 'CinvCode',
      type: 'text'
    },
    {
      title: '*产品名称',
      key: 'CinvName',
      type: 'text'
    },

    {
      title: '*单位',
      key: 'Unit',
      type: 'text'
    },
    {
      title: '*合同序号',
      key: 'CustCinvCode',
      type: 'text'
    },
    {
      title: '*合同名称',
      key: 'CustCinvName',
      type: 'text'
    },
    {
      title: '*合同型号',
      key: 'CustCinvAdd',
      type: 'text'
    },
    {
      title: '*单价',
      key: 'Price',
      type: 'text'
    },
    {
      title: '*数量',
      key: 'Quantity',
      type: 'text'
    },
    {
      title: '税率',
      key: 'Rate',
      type: 'text'
    },
    {
      title: '标记(新增不填)',
      key: 'Id',
      type: 'text'
    },
    {
      title: '交货日期',
      key: 'JFDate',
      type: 'date'
    },
    {
      title: '备注信息',
      key: 'Remark',
      type: 'text'
    },
    {
      title: '变更原因',
      key: 'BgRemark',
      type: 'text'
    },


  ],
  userList:[],
  checkData:{
    dialog:false,
    loading:false,
    data:[],
    title:'审批详情'
  },
  formViewData:{
    dialog:false,
    loading:false,
    data:[],
    title:'合同详情'
  }
})

//表单配置
const opts = ref({
  JobNum: {
    label: '工作号',
    placeholder: '请输入工作号',
    comp: 'el-input',
    bind: {
      size: 'small'
    }
  },
  CustCode: {
    label: '客户',
    placeholder: '请选择客户',
    comp: 't-select',
    isSelfCom: true,
    bind: {
      valueCustom: 'cCusCode',
      labelCustom: 'CustName',
      optionSource: cubasdoc.data,
      size: 'small'
    }
  },
  Type: {
    label: '合同类别',
    placeholder: '请选择合同类别',
    comp: 't-select',
    selectchange:function(){console.log(this)},
    isSelfCom: true,
    bind: {
      size: 'small',
      valueCustom: 'code',
      labelCustom: 'label',
      optionSource: [
        {
          code: '0',
          label: '正式合同'
        },
        {
          code: '1',
          label: '虚拟合同'
        }
      ]
    }
  },
  State: {
    label: '状态',
    placeholder: '请选择状态',
    comp: 't-select',
    isSelfCom: true,
    bind: {
      size: 'small',
      valueCustom: 'code',
      labelCustom: 'label',
      optionSource: [
        {
          code: '0',
          label: '开立'
        },
        {
          code: '1',
          label: '待审核'
        },
        {
          code: '2',
          label: '已审核'
        },
        {
          code: '3',
          label: '已关闭'
        }
      ]
    }
  },

  DeliveryDate: {
    label: '交付日期',
    comp: 't-date-picker',
    span: 1,
    bind: {
      size: 'small',
      type: 'daterange'
    }
  },
  // CreateFrom: {
  //   label: '制单日期',
  //   comp: 't-date-picker',
  //   span: 1,
  //   bind: {
  //     size: 'small',
  //     type: 'daterange'
  //   }
  // },

  CreateBy: {
    bind: {
      size: 'small',
    },
    label: '制单人',
    comp: 'el-input'
  }
})

//选择项
const cusoptions = ref([])

// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryData)
  //转换查询参数
  return {
    ContractType: data.ContractType?.value,
    CustCode: data.CustCode?.value,
    CustName: data.CustName?.value,
    CreateBy: data.CreateBy?.value,
    PSType: data.PSType?.value,
    IsMoudels: false,
    JobNum: data.JobNum?.value,
    State: data.State?.value,
    Type: data.Type?.value,
    CreateFrom:
      data.CreateFrom?.value && data.CreateFrom?.value[0] ? data.CreateFrom?.value[0] : null,
    CreateTo: data.CreateFrom?.value && data.CreateFrom?.value[1] ? data.CreateFrom?.value[1] : null,
    // IsBL:'是',
    IsBeginning:true
  }
})

// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data
  state.table.currentPage =1
  state.table.pageSize = 10
  getData()
}

// 点击查询按钮
const conditionDoligEnter = (data: any) => {
  getDigData()
}
const httypechanges=()=>
{
  console.log(this)
}
// 最终参数获取
const getQueryDigData = computed(() => {
  const data = toRefs(state.queryData)
  //转换查询参数
  return {
    ContractType: data.ContractType?.value,
    CustCode: data.CustCode?.value,
    CustName: data.CustName?.value,
    CreateBy: data.CreateBy?.value,
    PSType: data.PSType?.value,
    IsMoudels: true,
    State: '2',
    Type: data.Type?.value,
    CreateFrom:
      data.CreateFrom?.value && data.CreateFrom?.value[0] ? data.CreateFrom?.value[0] : null,
    CreateTo: data.CreateFrom?.value && data.CreateFrom?.value[1] ? data.CreateFrom?.value[1] : null
  }
})

// 清空表单
const clearCondition = () => {
  state.formData = {
    Main: {},
    SubList: [],
    TremZF: [],
    TremTO: [],
    TremTC: [],
    TremQA: [],
    TremFM: [],
    TremDR: [],
    TremD: [],
    TremOther: [],
    TremYS: [],
    TremBM: [],
    TremJF: [],
    TremBZ: [],
    ContractFile: []
  }
}

// 选择当前页码
const sizeChange = val => {

  state.table.pageSize = val
  getData()
}
// 选择当前页码
const pageChange = val => {

  state.table.currentPage = val
  getData()
}

// 获取数据
const getData = async () => {
  // state.loading = true
  getQueryData.value.PageIndex = state.table.currentPage
  getQueryData.value.PageSize = state.table.pageSize
  let data = await getHTByPage(getQueryData.value)

  if (data.Code === 'OK') {
    state.table.data = data.Data
    state.table.total = data.Count
  }
  state.loading = false
}

// 获取数据
const getDigData = async () => {
  let data = await getHTByPage(getQueryDigData.value)
  if (data.Code === 'OK') {
    state.tablecz.data = data.Data
    state.tablecz.total = data.Count
  }
}

//过滤单位
const cnvbasdocMethod = query => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter(its => {
        return (
          its.cCusCode.toLowerCase().includes(query.toLowerCase()) ||
          its.ccusabbname.toLowerCase().includes(query.toLowerCase())
        )
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

function updateContarctInfo(e) {
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.find(item => item.ContractNum === e)
  if (contractInfo) {
    //赋值项目名称
    state.formData.EntryName = contractInfo?.ProjectName
    state.formData.JobNum = contractInfo?.JobNum

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)
  }
}

//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })


  if (Data?.SubList) {
    //赋值合同明细
    state.editTable.data = Data.SubList
  }
}

//打开新增窗口
function addHandle() {
  clearCondition()

  //深度复制
  state.formData.Main = {
    Ddate: parseTime(new Date(), '{y}-{m}-{d}'),
    DDate2: parseTime(new Date(), '{y}-{m}-{d}'),
    Rate: 13,
    IsMoudels: false,
    IsMoudel: false,
    IsCompliance: true,
    JSJDFile: [],
    TDYSJDFile: [],
    JHYSJDFile: []
  }
  state.isAdd = true
  state.selecthttypechange=(vl)=>
  {
    console.log(vl)
  }
  state.isBg = true
  state.dialogSelectEnt = true
  state.isShowSubBut = true
}
//打开新增窗口
function importHandle() {
  clearCondition()
  state.upload.open = true
}

//关闭弹窗
function closeDialog() {
  state.dialogSelectEnt = false
  ishowfile.value=false;
  htlbselect.off('select-changed');
  reset()
}

// 添加数据条数
const num = ref(1)
const singleEdit: any = ref(null)
// 添加数据
const add = () => {
  if (num.value > 0) {
    for (let i = 0; i < num.value; i++) {
      state.editTable.data.push({})
    }
  }
}
// 重置表单
const reset = () => {
  state.coseData = []
  state.defaultSelectVal = []
  state.editTable.data = []
  singleEdit.value?.resetFields()
}

//下拉表格选择数据
const selectionChange = e => {
  state.coseData = e

}

//下拉表格选择数据
const selecUpdateChange = e => {
  // state.ids = e.map(item => item.Id)
  state.selectedRow = e

}

//选择标的
const addToTable = () => {
  if (state.coseData.length <= 0) {
    ElNotification.error({
      title: '提示',
      message: '请选择标的',
      offset: 200
    })
    return
  }


  state.coseData.forEach(item => {
    //相同数据不能添加
    if (state.clumTable.data.find(item1 => item1.Id === item.Id || item1.ConSubId === item.Id)) {
      ElMessage({
        message: item.CinvName + '已存在，请勿重复添加',
        type: 'warning'
      })

      return
    }
    let Qty = {
      ...item,
      Qty: item.Quantity,
      ConSubId: item.Id
    }
    state.clumTable.data.push(Qty)
  })
}

//校验表单需要定义ref
let formRef = ref({})
let TremTO = ref({})
let TremTC = ref({})
let TremQA = ref({})
let TremFM = ref({})
let TremDR = ref({})
let TremD = ref({})
let TremBM = ref({})
let TremOther = ref({})
let TremYS = ref({})
let TremJF = ref({})
let TremBZ = ref({})
let ContractFile = ref({})

const checkFild = checkFildsStore()
// 提交表单


const submitForm = debounce(
    async () => {
      checkFild.cliear()
      state.loading = true
      try {
        lding.value=true;
        unref(formRef).validateTable()
        setTimeout(async () => {
          if (checkFild.filds.length == 0) {
            const data = JSON.parse(JSON.stringify(state.formData))

            console.log(data, 'data')
            try {
              await SaveQCHT(data)
            }catch (e){
              ElNotification.error({
                title: '提示',
                message: e.message,
                offset: 200
              })
              return;
            }

            // Process array fields
            const arrayFields = ['PhasedFile', 'Payment', 'JSJDFile', 'TDYSJDFile', 'JHYSJDFile']
            arrayFields.forEach(field => {
              if (data.Main[field]?.length > 0) {
                data.Main[field] = state.formData.Main[field].join(',')
              } else {
                data.Main[field] = ''
              }
            })

            let res ={}
            //校验通过
            res =await SaveQCHT(data)
            lding.value=false;
            if (res.Code === 'OK') {
              ElNotification.success({
                title: '提示',
                message: '保存成功',
                offset: 200
              })
              setTimeout(async () => {
                await getData()
              }, 1000)
              closeDialog()
            } else {
              ElNotification.error({
                title: '提示',
                message: res.Result,
                offset: 200
              })
            }
          }
        }, 2000)
      } catch (e) {
        console.log(e);
      } finally {
        state.loading = false
        lding.value=false;
        // state.isqc=false
      }
    },
    false,
    1000
)

function printHandle(res) {

  window.open(import.meta.env.VITE_APP_PRINT_API + res.Id)
}

async function versionHandle(res) {
  //查询版本
  let { Data, Code } = await getContractVersion({
    ContractNum: res.ContractNum,
    versionNum: res.versionNum,
    BaseCode: res.BaseCode
  })
  if (Code === 'OK') {
    state.drawer.gridData = Data
    state.drawer.open = true

  }
}

function handlChange(row) {
  ElMessageBox.confirm('确认将工作号为【'+row.JobNum+'】的合同转为正式合同？', '审核提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      //调用查询合同详细信息
      let re = await getContractInfo({ id: row.Id })

      if (re.Code === 'OK') {
        state.formData = re.Data
        state.formData.Type = 'ZH'
        state.formData.Main.IsMoudels = false
        state.formData.Main.Type = '0'

        //校验通过
        let res = await SaveQCHT(state.formData)
        if (res.Code === 'OK') {
          ElNotification.success({
            title: '提示',
            message: '转换成功',
            offset: 200
          })
          await getData(1)
        } else
          ElNotification.error({
            title: '提示',
            message: res.Result,
            offset: 200
          })
      }
    })
    .catch(() => {})
}

//删除表单
function deleteHandles(row) {
  const ids = row.Id ? [row.Id] : state.ids


  ElMessageBox.confirm('确认删除工作号为【'+row.JobNum+'】的合同？请仔细核对数据，删除后无法恢复！', '审核提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await delHT({ Ids: ids })
      if (res.Code === 'OK') {
        ElNotification.success({
          title: '提示',
          message: '删除成功',
          offset: 200
        })
        await getData(1)
      } else
        ElNotification.error({
          title: '提示',
          message: res.Result,
          offset: 200
        })

      await getData(1)
    })
    .catch(() => {})
}

/** 下载模板操作 */
function importTemplate() {
  window.open(import.meta.env.VITE_APP_BASE_API + '/Content/Flie/moudel.xlsx')
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  state.upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  state.upload.open = false
  state.upload.isUploading = false
  getData()
}

//页面加载查询后端数据
onMounted(() => {
  // getDigData()
  getData()
  initRoleList()
  getUserList()
  //console.log(88888);

})

const radioChange = async row => {

  clearCondition()
  //调用查询合同详细信息
  if (row.Id != undefined) {
    let res = await getContractInfo({ id: row.Id })

    if (res.Code === 'OK') {
      state.formData = res.Data
      state.formData.Main.Id = null
      //state.formData.Type = "BJ"
      state.isShowSubBut = true
      state.dialogSelectEnt = true
      state.formData.Main.IsMoudels = false
      state.formData.Main.ContractNum = null
      state.formData.Main.ContractName = null
      state.formData.Main.IsMoudel = true
      state.isBg = true
      if (state.formData.Main.PhasedFile) {
        //转换为数组
        state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(',')
      } else {
        state.formData.Main.PhasedFile = []
      }
      if (state.formData.Main.Payment?.length > 0) {
        //转换为数组
        state.formData.Main.Payment = state.formData.Main.Payment.split(',')
      } else {
        state.formData.Main.Payment = []
      }
      if (state.formData.Main.TDYSJDFile) {
        //转换为数组
        state.formData.Main.TDYSJDFile = state.formData.Main.TDYSJDFile.split(',')
      } else {
        state.formData.Main.TDYSJDFile = []
      }
      if (state.formData.Main.JHYSJDFile) {
        //转换为数组
        state.formData.Main.JHYSJDFile = state.formData.Main.JHYSJDFile.split(',')
      } else {
        state.formData.Main.JHYSJDFile = []
      }

      if (state.formData.Main.JSJDFile) {
        //转换为数组
        state.formData.Main.JSJDFile = state.formData.Main.JSJDFile.split(',')
      } else {
        state.formData.Main.JSJDFile = []
      }
      // state.dialogSelectEnt = true
      // state.title = "修改合同录入"
    }
  } else {
    state.formData = {
      isModule: false,
      isModules: false,
      Id: null,
      Main: {
        PhasedFile: [],
        Payment: []
      }
    }
    state.isShowSubBut = true
    state.dialogSelectEnt = true
    state.isBg = false
  }
}

const updateSubList = e => {

  state.formData.SubList = e


}

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同输入' })
  state.roleList = res.items
}


//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}
</script>
